<?php
namespace api\modules\lianzhuo\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use izyue\admin\models\Member;
use izyue\admin\models\MemberSearch;
use izyue\admin\models\DataOrder;
use izyue\admin\models\DataOrderSearch;
use izyue\admin\models\FlowValNo;
use izyue\admin\models\FlowValNoSearch;
use linslin\yii2\curl;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public $apikey = 'b720665af5336e1d18510c3c207cfe5b';
    public $account = 'aimingtian';
    public $url = 'http://www.llkc8.com/api/flowService.do';
    public $backurl = 'https://www.tieba8.com/api/web/lianzhuo/site/back';

    public function init(){
        $this->enableCsrfValidation = false; //取消post csrf验证 否则无法post数据
    }

    public function actionSubmit()
    {   
        //echo strtoupper(MD5('account=aimingtian&id=GD1008610100&mobile=15220038141&key=b720665af5336e1d18510c3c207cfe5b'));exit;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $post = Yii::$app->request->post();
        $mobile = $this->GetMobileArea($post['phone_no']);
        //print_R($mobile);exit;
        if ($mobile['catName'] == "中国移动") {
            $operator = 1;
        } elseif ($mobile['catName'] == "中国联通") {
            $operator = 2;
        } elseif ($mobile['catName'] == "中国电信"){
            $operator = 3;
        }
        $goodsid = FlowValNo::find()->where(['operator' => $operator, 'province' => $mobile['province'],'val' => $post['flow_val'],'isprovince' => $post['scope']])->one();
        //print_r($goodsid);exit;
        $sign   =   strtoupper(MD5(
            'account=' . $this->account . 
            '&id=' . $goodsid['no'] . 
            '&mobile=' . $post['phone_no'] . 
            '&notifyurl=' . $this->backurl . 
            '&key=' . $this->apikey));
        $param = array(
            'action' => 'createOrder.do',
            'v' => '1.0',
            'account' => $this->account,
            'mobile' => $post['phone_no'],
            'id' => $goodsid['no'],
            'notifyurl' => $this->backurl,
            'sign' => $sign,
            'othersoId' => $post['out_order_id'],
        );
        //print_r($param);exit;
        file_put_contents(Yii::$app->basePath."/api_lianzhuo_submit_data.txt", print_r($param,true),FILE_APPEND);
        $return = $this->curl_http($this->url,$param);
        //print_R($return);exit;
        file_put_contents(Yii::$app->basePath."/api_lianzhuo_submit_curl_return.txt", print_r($return,true),FILE_APPEND);

        $return_array = json_decode($return,true);
        if ($return_array['code'] == '000') {
            $return_array_new = array(
                'result' => '0',
                'out_order_id' => $post['out_order_id'],
                'order_id' => $return_array['taskID']
                ); 
        } else {
            $return_array_new = $return_array;
        }
        return $return_array_new;
    }
    //余额查询接口
    public function actionBlance()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $sign   =   strtoupper(MD5(
            'account=' . $this->account . 
            '&key=' . $this->apikey));
        //echo $sign;exit;
        //$url = 'http://www.llkc8.com/api/flowService.do';
        $param = array(
            'action' => 'getBalance.do',
            'v' => 1.0,
            'account' => $this->account,
            'sign' => $sign,
        );
        $return = $this->curl_http($this->url,$param);
        return json_decode($return,true);
          
    }
    //订单查询接口
    public function actionQuery()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $post = Yii::$app->request->post();
        $sign   =   strtoupper(MD5(
            'account=' . $this->account . 
            '&taskid=' . $post['taskid'] . 
            '&key=' . $this->apikey));
        //echo $sign;exit;
        
        $param = array(
            'action' => 'queryOrder.do',
            'v' => 1.0,
            'account' => $this->account,
            'taskid' => $post['taskid'],
            'sign' => $sign,
        );
        //print_r($param);exit;
        $return = $this->curl_http($this->url,$param);
        $array = json_decode($return,true);
        return $array;
    }
    //回调地址接口
    public function actionBack()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        $param = Yii::$app->request->post();
        file_put_contents(Yii::$app->basePath."/api_lianzhuo_back.txt", print_r($param,true),FILE_APPEND);
        //echo 1;exit;
        if ($param['result'] == "0") {
            $param['status'] = 3;
        } else {
            $param['status'] = 4;
        }
        file_put_contents(Yii::$app->basePath."/api_lianzhuo_return.txt", print_r($param,true),FILE_APPEND);
        $order = $this->GetOrder($param);
        $param['out_order_id'] = $order['out_order_id'];
        $this->UpdateOrderStatus($param);
        $backurl = $this->GetBackUrl($param);
        
        $curl_array = array(
                    'order_id' => $param['taskid'], 
                    'out_order_id' => $param['out_order_id'], 
                    'status' => $param['status'],
                    'completion_time' => time(),
                    'err_desc' => $param['resultdesc'],
                    );
        $return = $this->curl_http($backurl,$curl_array);

        //如果没有返回则定时回调
        return $return;  
    }
    public function actionBacks()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        $url = Yii::$app->request->hostInfo . "/api/web/lianzhuo/site/query";
        $post = Yii::$app->request->post();
        $backurl = Yii::$app->request->hostInfo . "/api/web/v1/site/back";
        $res = DataOrder::find()->where(['status' => [2,1],'apiid' => 4])->limit(10)->all();
        $param = array();
        foreach ($res as $value) {
            $param['out_order_id'] = $value['out_order_id'];
            $param['taskid'] = $value['out_order_id'];
            $backurl = $this->GetBackUrl($param);
            $return = $this->curl_http($url,$param);
            $return_array = json_decode($return,true);
            //print_R($return_array);exit;
            if (!empty($return_array['code'])) {
                if ($return_array['code'] == "002") {
                    $curl_array = array(
                        'order_id' => $param['out_order_id'],
                        'out_order_id' => $param['out_order_id'],
                        'status' => 3,
                        'completion_time' => time(),
                        'err_desc' => '',
                    );
                    $param['status'] = $curl_array['status'];
                    $return = $this->curl_http($backurl,$curl_array);
                    file_put_contents(Yii::$app->basePath."/api_lianzhuo_backs.txt", print_r($param,true),FILE_APPEND);
                    $this->UpdateOrderStatus($param);
                    echo 'UpdataOrderSuccess002';
                } elseif ($return_array['code'] == "003") {
                    $curl_array = array(
                        'order_id' => $param['out_order_id'],
                        'out_order_id' => $param['out_order_id'],
                        'status' => 4,
                        'completion_time' => time(),
                        'err_desc' => '充值失败',
                    );
                    $param['status'] = $curl_array['status'];
                    $return = $this->curl_http($backurl,$curl_array);
                    file_put_contents(Yii::$app->basePath."/api_lianzhuo_backs.txt", print_r($param,true),FILE_APPEND);
                    $this->UpdateOrderStatus($param);
                    echo 'UpdataOrderSuccess003';
                } elseif ($return_array['code'] == "004"){
                    $curl_array = array(
                        'order_id' => $param['out_order_id'],
                        'out_order_id' => $param['out_order_id'],
                        'status' => 5,
                        'completion_time' => time(),
                        'err_desc' => '充值异常',
                    );
                    $param['status'] = $curl_array['status'];
                    //$return = $this->curl_http($backurl,$curl_array);
                    file_put_contents(Yii::$app->basePath."/api_lianzhuo_backs.txt", print_r($param,true),FILE_APPEND);
                    $this->UpdateOrderStatus($param);
                    echo 'UpdataOrderSuccess004';
                } else {
                    $curl_array = array(
                        'order_id' => $param['out_order_id'],
                        'out_order_id' => $param['out_order_id'],
                        'status' => 2,
                        'completion_time' => time(),
                        'err_desc' => '',
                    );
                    $param['status'] = $curl_array['status'];
                    //$return = $this->curl_http($backurl,$curl_array);
                    file_put_contents(Yii::$app->basePath."/api_lianzhuo_backs.txt", print_r($param,true),FILE_APPEND);
                    $this->UpdateOrderStatus($param);
                    echo 'UpdataOrderSuccess000';
                }  
            }
            file_put_contents(Yii::$app->basePath."/api_lianzhuo_backs_orderid.txt", print_r($value['id'],true),FILE_APPEND);
            

        }
        //file_put_contents(Yii::$app->basePath."/api_lianzhuo_backs_orderid.txt", print_r($id,true),FILE_APPEND);
        echo 1;
        

    }
    public function UpdateOrderStatus($param) { 
        $res = DataOrder::find()->where(['out_order_id' => $param['out_order_id']])->one();
        DataOrder::updateAll(
            array('status'=>$param['status'],'ordersn'=>$param['taskid']),
            'out_order_id=:out_order_id',
            array(':out_order_id'=>$res['out_order_id'])
            );
    }
    public function GetOrder($param) {
        $res = DataOrder::find()->where(['ordersn' => $param['taskid']])->one();
        return $res;
    }
    public function GetBackUrl($param){
        $res = DataOrder::find()->where(['out_order_id' => $param['out_order_id']])->one();
        $info = Member::findOne($res['mid']);
        return $info['back_url'];

    }
    public function curl_http($url,$param){
        $curl = new curl\Curl();
        $response = $curl->setOption(
                CURLOPT_POSTFIELDS, 
                http_build_query($param)
                )
            ->post($url);
        return $response;
    }
    public function GetMobileArea($mobile) {
        $sms = array('province'=>'', 'supplier'=>'');    //初始化变量
        //根据淘宝的数据库调用返回值
        $url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=".$mobile."&t=".time();
        $num = 0;
        do {
            $content = file_get_contents($url);
            $html = iconv("gb2312", "utf-8//IGNORE",$content);
            $data = explode(',', $html);
            @$province = explode(':', $data[1]);
            @$catname = explode(':', $data[2]);
            @$array = array(
                trim($province[0]) => str_replace("'","",$province[1]),
                trim($catname[0]) => str_replace("'","",$catname[1])
            );
            $num++;
        } while (empty($array['catName']) && $num < 10);
        return @$array;

    }


}
